package com.wss.common.utils.toast;

import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;

public class BaseToast extends ToastDialog {

    /**
     * 吐司消息 View
     */
    private Text mMessageView;

    public BaseToast(Context context) {
        super(context);
    }

    @Override
    public ToastDialog setComponent(Component component) {
        mMessageView = getMessageView(component);
        return super.setComponent(component);
    }

    public void setMessage(String msg) {
        mMessageView.setText(msg);
    }

    public Text getMessageView(Component component) {
        if (component instanceof Text) {
            return (Text) component;
        } else if (component instanceof ComponentContainer) {
            Text textView = findTextView((ComponentContainer) component);
            if (textView != null) {
                return textView;
            }
        }
        // 如果设置的布局没有包含一个 TextView 则抛出异常，必须要包含一个 TextView 作为 MessageView
        throw new IllegalArgumentException("The layout must contain a TextView");
    }

    /**
     * 递归获取 ViewGroup 中的 TextView 对象
     */
    private static Text findTextView(ComponentContainer group) {
        for (int i = 0; i < group.getChildCount(); i++) {
            Component view = group.getComponentAt(i);
            if (view instanceof Text) {
                return (Text) view;
            } else if (view instanceof ComponentContainer) {
                Text textView = findTextView((ComponentContainer) view);
                if (textView != null) {
                    return textView;
                }
            }
        }
        return null;
    }
}
